"""
Module Usage:
rgb_to_names((255,255,255)) --> rgb_to_names((255,255,255)): white

We will use a data structure called KDTree. 
It will look for the closest matched hex code for our given RGBs that has a color name associated to it. 
You can read more about KDTree here.
RGB →(0.255.0), Hex Code →#00FF00, Color Name →lime
RGB →(178,34,34), Hex Code →#B22222, Color Name →firebrick
"""

# RGB to Color Names in Python — The Robust Way | by Mir AbdulHaseeb | CodeX | Jan, 2021 | Medium
# https://medium.com/codex/rgb-to-color-names-in-python-the-robust-way-ec4a9d97a01f#id_token=eyJhbGciOiJSUzI1NiIsImtpZCI6ImZkMjg1ZWQ0ZmViY2IxYWVhZmU3ODA0NjJiYzU2OWQyMzhjNTA2ZDkiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL2FjY291bnRzLmdvb2dsZS5jb20iLCJuYmYiOjE2MTMwNDQ0ODAsImF1ZCI6IjIxNjI5NjAzNTgzNC1rMWs2cWUwNjBzMnRwMmEyamFtNGxqZGNtczAwc3R0Zy5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbSIsInN1YiI6IjExMTU1MzY0MzU0MjM5NDM1NjEzNCIsImVtYWlsIjoibGlhbmcyNjk0NDA4NzdAZ21haWwuY29tIiwiZW1haWxfdmVyaWZpZWQiOnRydWUsImF6cCI6IjIxNjI5NjAzNTgzNC1rMWs2cWUwNjBzMnRwMmEyamFtNGxqZGNtczAwc3R0Zy5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbSIsIm5hbWUiOiJMaWFuZyBMaWFuZyIsInBpY3R1cmUiOiJodHRwczovL2xoMy5nb29nbGV1c2VyY29udGVudC5jb20vYS0vQU9oMTRHZ0VtcU5nX0toQzhINk9URXRrYnFOZHEybHdRWkxkNWdvM3FJbkM9czk2LWMiLCJnaXZlbl9uYW1lIjoiTGlhbmciLCJmYW1pbHlfbmFtZSI6IkxpYW5nIiwiaWF0IjoxNjEzMDQ0NzgwLCJleHAiOjE2MTMwNDgzODAsImp0aSI6IjFhNDZiZDM1OTM4M2I0MWM3MGFlZjQyN2U5ZjM3ZTBhNWI5ZTllMzcifQ.0qK_KoU4V4RAzIUlE-oP51TUAzQlFOlWB4TPdM0Tr0LM-rC32qXAP4rN1Qt5zQrPa2uKQjB_EaYaGFHb3Zndadt-9_4dn14orgTCgxTKhcwrQrls4tDl2BM_4Fxbjuo-xkNjs26dYop0IauSDwy6f6U14aFqh2FI26BI2ThEqA9_YZt7b5FwiCmsKG6r-npSNoKhM9mdbZ0cmtQbACxFPASXikOmSlT51VTDVyOUBR-OzM7sMyqafklSOMZuK9n1sXBAB-4MwvYJnrgelOo8wtT4IaAwYZIDW0JSJe1sND3uiRaHbblY2m8seXw8-YRkWbTHiu-lUkCzuNVV3PThoA

from scipy.spatial import KDTree
from webcolors import (
    CSS3_HEX_TO_NAMES,
    hex_to_rgb,
)


def rgb_to_names(rgb_tuple):
    
    # a dictionary of all the hex and their respective names in css3
    css3_db = CSS3_HEX_TO_NAMES
    names = []
    rgb_values = []
    for color_hex, color_name in css3_db.items():
        names.append(color_name)
        rgb_values.append(hex_to_rgb(color_hex))
    
    kdt_db = KDTree(rgb_values)
    distance, index = kdt_db.query(rgb_tuple)
    return f'closest match: {names[index]}'